package com.king.sqlSession;

import com.king.pojo.Configuration;
import com.king.pojo.MapperStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * @ClassName: DefaultSqlSession
 * @Description: TODO
 * @Author: wangchangyong
 * @Date: 2020/3/26 21:33
 * @Version: 1.0.0
 **/
public class DefaultSqlSession implements Sqlsession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> list = null;
        try {
            list = simpleExecutor.query(configuration, mapperStatement, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多");
        }
    }

    @Override
    public int insert(String statementId, Object... params) {
        return update(statementId, params);
    }

    @Override
    public int update(String statementId, Object... params) {
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        int rows = 0;
        try {
            rows = simpleExecutor.update(configuration, mapperStatement, params);
        } catch (Exception e) {
            throw new RuntimeException("数据库更新异常", e);
        }
        return rows;
    }

    @Override
    public int delete(String statementId, Object... params) {
        return update(statementId, params);
    }

    @Override
    public <T> T getMapper(Class<T> mapperClass) {

        // 使用JDK动态代理生成DAO接口代理对象
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            /**
             * @param proxy  当前代理对象引用
             * @param method 当前被调用方法的引用
             * @param args   传递的参数
             * @return
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // statementId
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className+"."+methodName;
                // params = args
                MapperStatement ms = configuration.getMapperStatementMap().get(statementId);
                // SQL语句操作关键字
                String type = ms.getSql().substring(0, 6);

                // 查询
                if (type.equalsIgnoreCase("select")) {
                    // 获取被调用方法的返回值类型
                    Type genericReturnType = method.getGenericReturnType();
                    // 判断是否进行泛型类型参数化
                    if (genericReturnType instanceof ParameterizedType) {
                        List<Object> objects = selectList(statementId, args);
                        return objects;
                    }
                    return selectOne(statementId, args);
                } else if (type.equalsIgnoreCase("insert")) {
                    // 新增
                    return insert(statementId, args);
                } else if (type.equalsIgnoreCase("update")) {
                    // 更新
                    return update(statementId, args);
                } else if (type.equalsIgnoreCase("delete")) {
                    // 删除
                    return delete(statementId, args);
                } else {
                    throw new Exception("Unknown execution method for: " + methodName);
                }
            }
        });
        return (T) proxyInstance;
    }
}
